<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\event\RouteLoaded;
use think\facade\Config;
use think\facade\Db;
use think\facade\Route;

class MakeFrontRoute extends Command
{
    protected function configure()
    {
		$this->setName('make_front_route')
			->setDescription('自动生成前端路由配置到 client/src/config/api.ts文件中');
    }

    protected function execute(Input $input, Output $output)
    {
	    // todo 使用命令自动生成前端路由配置文件
	    $route_path  = app_path().'/admin/route/app.php';
	    if (!file_exists($route_path)) {
			$output->writeln("路由文件[$route_path]不存在");
			exit();
	    }
	    include $route_path;
	    $this->app->event->trigger(RouteLoaded::class);
	    $route_list =  Route::getRuleList();
	    $api = [];
	    foreach ($route_list as $route) {
		    if (in_array($route['method'],['get','post'])) {
			    $rule = explode('/', $route['rule']);
			    $api['base'] = "/$rule[0]/";
			    $api[$rule[1]][$rule[2]] = "{$route['method']}:/$rule[1]/$rule[2]";
		    }
	    }
		$api_str = str_replace('\\',"",json_encode($api));
		$content = <<<EOF
export default $api_str;
EOF;
		file_put_contents(root_path().'client/src/config/api.ts', $content);
    }
}
